package com.wxg.config;

import com.wxg.utils.IpUtil;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.UUID;

/**
 * 自定义限流标志的key，多个维度可以从这里入手
 * exchange对象中获取服务ID、请求信息，用户信息等
 */
@Component
public class RequestRateLimiterConfig {

    /**
     * ip地址限流
     * @return 限流key
     */
    @Bean
    @Primary
    public KeyResolver remoteAddressKeyResolver() {
//        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
        return exchange -> Mono.just(IpUtil.getIpAddress(exchange.getRequest()));
    }

    /**
     * 请求路径限流
     * @return 限流key
     */
    @Bean
    public KeyResolver urlKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * token限流
     * @return 限流key
     */
    @Bean
    public KeyResolver tokenKeyResolver() {
        return exchange -> Mono.just(
                Optional.ofNullable(exchange.getRequest().getHeaders().getFirst("token"))
                .orElseGet(()-> UUID.randomUUID().toString().replaceAll("-", ""))
        );
    }

    @Bean
    public KeyResolver ipAndUrlResolver(){
        return exchange -> Mono.just(
                IpUtil.getIpAddress(exchange.getRequest())+":"+exchange.getRequest().getPath().value()
        );
    }
}
